<?php

namespace app\admin\controller;

use think\Controller;
use think\controller\Rest;
use think\Db;
use think\Log;
use think\Request;

class Index extends Common
{
    public function index()
    {
        $news_data = getNewData(2);
        $live_video_data = getLiveVideoData();
        $live_music_data = getLiveMusicData();
        
        $siren_data = getSirenData();
        
        $this->assign('web_news_list', $news_data['web_list']);
        $this->assign('app_news_list', $news_data['app_list']);
        $this->assign('web_all_news_count', $news_data['web_all_news_count']);
        $this->assign('app_all_news_count', $news_data['app_all_news_count']);
        $this->assign('web_today_news_count', $news_data['web_today_news_count']);
        $this->assign('app_today_news_count', $news_data['app_today_news_count']);
        $this->assign('web_error_count', $news_data['web_error_count']);
        $this->assign('app_error_count', $news_data['app_error_count']);
        $this->assign('live_video_data', $live_video_data);
        $this->assign('live_music_data', $live_music_data);
        $this->assign('siren_data', $siren_data);
        $this->assign('siren_data_json', json_encode($siren_data));
        
        return $this->fetch();
    }
    
    /**
     * 网页监测记录
     * */
    public function checkIndexLogList()
    {
        $input = Request()->param();
        
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $style = $input['style'];

//        $where['status'] = 0;
        
        if (!empty($start_time) && empty($end_time)) {
            $where["check_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["check_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["check_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        
        if ($style) $where['style'] = $style;
        
        $list = Db::name('check_index_log')->where($where)->order('status asc,id desc')->paginate()->each(function ($v) {
            switch ($v['style']) {
            case 1:
                $style_desc = '已查看';
                break;
            case 2:
                $style_desc = '已处理';
                break;
            case 3:
                $style_desc = '暂不处理';
                break;
            default:
                $style_desc = '未处理';
            }
            $v['style_desc'] = $style_desc;
            
            return $v;
        });
        
        $all_count = Db::name('check_index_log')->count();
        $error_count = Db::name('check_index_log')->where(['status' => 0])->count();
        
        $this->assign('list', $list);
        $this->assign('all_count', $all_count);
        $this->assign('error_count', $error_count);
        
        $this->assign('title', '网页监测记录');
        
        return $this->fetch();
    }
    
    /**
     * 首页处理详情
     * */
    public function indexDetail()
    {
        $id = Request()->param('id');
        
        $time = time();
        if (Request()->isPost()) {
            $style = Request()->param('style');
            
            Db::startTrans();
            try {
                $data = [
                    'user_id' => session('id'),
                    'style' => $style,
                    'status' => $style == 2 ? 1 : 0,
                    'update_time' => $time
                ];
                Db::name('check_index_log')->where(['id' => $id])->update($data);
                
                $crontab_log_id = Db::name('check_index_log')->where(['id' => $id])->value('crontab_log_id');
                if ($crontab_log_id) Db::name('crontab_log')->where(['id' => $crontab_log_id])->setField('is_do', 1);
                
                Db::commit();
                adminReturn(1, '提交成功', url('checkIndexLogList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '提交失败');
            }
        } else {
            $info = Db::name('check_index_log')->where(['id' => $id])->find();
            
            if ($info['style'] == 0) Db::name('check_index_log')->where(['id' => $id])->update(['style' => 1, 'update_time' => $time]);
        }
        
        $this->assign('info', $info);
        $this->assign('title', '首页处理详情');
        
        return $this->fetch();
    }
    
    /**
     * 新闻监测记录
     * */
    public function checkNewsLogList()
    {
        $input = Request()->param();
        
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $terminal = $input['terminal'];
        $style = $input['style'];

//        $where['status'] = 0;
        
        if (!empty($start_time) && empty($end_time)) {
            $where["check_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["check_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["check_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        
        if ($terminal) $where['terminal'] = $terminal;
        
        if ($style) $where['style'] = $style;
        
        $build_sql = Db::name('check_news_log')->order('id desc')->buildSql();
        $list_sql = Db::table($build_sql . ' a')
            ->field('id,news_id,terminal,check_time,status,style')
            ->order('status asc,id desc')
            ->group('news_id')
            ->buildSql();
        
        $list = Db::table($list_sql . ' b')
            ->where($where)
            ->paginate()->each(function ($v) {
                switch ($v['style']) {
                case 1:
                    $style_desc = '已查看';
                    break;
                case 2:
                    $style_desc = '已处理';
                    break;
                case 3:
                    $style_desc = '暂不处理';
                    break;
                default:
                    $style_desc = '未处理';
                }
                $v['style_desc'] = $style_desc;
                
                $news_info = Db::name('news')->where(['id' => $v['news_id']])->find();
                $v['title'] = $news_info['title'];
                $v['url'] = $news_info['url'];
                $v['publish_time'] = $news_info['publish_time'];
                
                return $v;
            });
        
        $error_count = Db::table($list_sql . ' b')->where($where)->where(['status' => 0])->count();
        $this->assign('error_count', $error_count);
        
        $this->assign('list', $list);
        $this->assign('title', '新闻监测记录');
        
        return $this->fetch();
    }
    
    /**
     * 新闻处理详情
     * */
    public function newsDetail()
    {
        $id = Request()->param('id');
        
        $time = time();
        if (Request()->isPost()) {
            $style = Request()->param('style');
            $news_id = Request()->param('news_id');
            
            Db::startTrans();
            try {
                $data = [
                    'user_id' => session('id'),
                    'style' => $style,
                    'status' => $style == 2 ? 1 : 0,
                    'update_time' => $time
                ];
                Db::name('check_news_log')->where(['id' => $id])->update($data);
                
                if ($style == 2) {
                    // 已处理
                    Db::name('news')->where(['id' => $news_id])->setField('status', 1);
                }
                
                $crontab_log_id = Db::name('check_news_log')->where(['id' => $id])->value('crontab_log_id');
                if ($crontab_log_id) Db::name('crontab_log')->where(['id' => $crontab_log_id])->setField('is_do', 1);
                
                Db::commit();
                adminReturn(1, '提交成功', url('checkNewsLogList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '提交失败');
            }
        } else {
            $info = Db::name('check_news_log log')
                ->join('monitor_news l', 'log.news_id = l.id')
                ->field('log.id,log.news_id,log.terminal,l.publish_time,log.status,log.check_time,l.url,log.log_file_path,log.style,log.html_content')
                ->where(['log.id' => $id])
                ->find();
            
            if ($info) {
                $news_info = Db::name('news')->where(['id' => $info['news_id']])->find();
                $info['title'] = $news_info['title'];
                $info['publish_time'] = $news_info['publish_time'];
                
                if ($info['style'] == 0) Db::name('check_news_log')->where(['id' => $id])->update(['style' => 1, 'update_time' => $time]);
            }
        }
        
        $this->assign('info', $info);
        $this->assign('title', '新闻处理详情');
        
        return $this->fetch();
    }
    
    /**
     * 删除新闻
     * */
    public function delNews()
    {
        $id = Request()->param('id');
        
        if (empty($id)) adminReturn(2, '新闻ID缺失');
        
        $info = Db::name('news')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                Db::name('news')->where(['id' => $id])->delete();
                Db::name('check_news_log')->where(['news_id' => $id])->delete();
                Db::name('crontab_log')->where(['course_id' => $id, 'type' => 2])->delete();
                
                Db::commit();
                adminReturn(1, '新闻删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '新闻删除失败');
            }
        } else {
            adminReturn(2, '新闻不存在或已删除');
        }
    }
    
    /**
     * 新闻监测历史记录
     * */
    public function checkNewsLogResultList()
    {
        $news_id = Request()->param('news_id');
        
        $list = Db::name('check_news_log')->where(['news_id' => $news_id])->order('id desc')->paginate();
        
        $this->assign('list', $list);
        $this->assign('title', '新闻监测历史记录');
        
        return $this->fetch();
    }
    
    /**
     * 音视频监测记录
     * */
    public function checkLiveLogList()
    {
        $input = Request()->param();
        
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $terminal = $input['terminal'];
        $style = $input['style'];

//        $where['status'] = 0;
        
        if (!empty($start_time) && empty($end_time)) {
            $where["check_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["check_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["check_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        
        if ($terminal) $where['terminal'] = $terminal;
        
        if ($style) $where['style'] = $style;
        
        $build_sql = Db::name('check_live_log')->order('id desc')->buildSql();
        $list_sql = Db::table($build_sql . ' a')
            ->field('id,live_id,terminal,check_time,status,type,style')
            ->order('status asc,id desc')
            ->group('live_id')
            ->buildSql();
        
        $list = Db::table($list_sql . ' b')
            ->where($where)
            ->paginate()->each(function ($v) {
                switch ($v['style']) {
                case 1:
                    $style_desc = '已查看';
                    break;
                case 2:
                    $style_desc = '已处理';
                    break;
                case 3:
                    $style_desc = '暂不处理';
                    break;
                default:
                    $style_desc = '未处理';
                }
                $v['style_desc'] = $style_desc;
                
                $live_info = Db::name('live l')->join('monitor_live_type t', 'l.type_id = t.id')->field('l.name title,l.url,t.name')->where(['l.id' => $v['live_id']])->find();
                $v['type_name'] = $live_info['name'] ?: '';
                $v['title'] = $live_info['title'] ?: '';
                $v['url'] = $live_info['url'] ?: '';
                
                return $v;
            });
        
        $where['type'] = 1;
        $error_video_count = Db::table($list_sql . ' b')->where($where)->where(['status' => 0])->count();
        
        $where['type'] = 2;
        $error_music_count = Db::table($list_sql . ' b')->where($where)->where(['status' => 0])->count();
        
        $this->assign('list', $list);
        $this->assign('error_video_count', $error_video_count);
        $this->assign('error_music_count', $error_music_count);
        $this->assign('title', '音视频监测记录');
        
        return $this->fetch();
    }
    
    /**
     * 音视频处理详情
     * */
    public function liveDetail()
    {
        $id = Request()->param('id');
        
        $time = time();
        if (Request()->isPost()) {
            $style = Request()->param('style');
            $live_id = Request()->param('live_id');
            
            Db::startTrans();
            try {
                $data = [
                    'user_id' => session('id'),
                    'style' => $style,
                    'status' => $style == 2 ? 1 : 0,
                    'update_time' => $time
                ];
                Db::name('check_live_log')->where(['id' => $id])->update($data);
                
                if ($style == 2) {
                    // 已处理
                    Db::name('live')->where(['id' => $live_id])->setField('status', 1);
                }
                
                $crontab_log_id = Db::name('check_live_log')->where(['id' => $id])->value('crontab_log_id');
                if ($crontab_log_id) Db::name('crontab_log')->where(['id' => $crontab_log_id])->setField('is_do', 1);
                
                Db::commit();
                adminReturn(1, '提交成功', url('checkLiveLogList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '提交失败');
            }
        } else {
            $info = Db::name('check_live_log log')
                ->join('monitor_live l', 'log.live_id = l.id')
                ->field('log.id,log.live_id,log.terminal,l.publish_time,log.status,log.check_time,l.url,log.log_file_path,log.style')
                ->where(['log.id' => $id])
                ->find();
            
            if ($info) {
                $type_name = Db::name('live l')->join('monitor_live_type t', 'l.type_id = t.id')->where(['l.id' => $info['live_id']])->value('t.name');
                $info['type_name'] = $type_name;
                
                $live_info = Db::name('live')->where(['id' => $info['live_id']])->find();
                $info['publish_time'] = $live_info['publish_time'];
                $info['url'] = $live_info['url'];
                
                if ($info['style'] == 0) Db::name('check_live_log')->where(['id' => $id])->update(['style' => 1, 'update_time' => $time]);
            }
        }
        
        $this->assign('info', $info);
        $this->assign('title', '音视频处理详情');
        
        return $this->fetch();
    }
    
    /**
     * 删除音视频
     * */
    public function delLive()
    {
        $id = Request()->param('id');
        
        if (empty($id)) adminReturn(2, '音视频ID缺失');
    
        $info = Db::name('live')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                Db::name('live')->where(['id' => $id])->delete();
                Db::name('check_live_log')->where(['live_id' => $id])->delete();
                Db::name('crontab_log')->where(['course_id' => $id, 'type' => ['IN', '3,4']])->delete();
                
                Db::commit();
                adminReturn(1, '音视频删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '音视频删除失败');
            }
        } else {
            adminReturn(2, '音视频不存在或已删除');
        }
    }
    
    /**
     * 音视频监测历史记录
     * */
    public function checkLiveLogResultList()
    {
        $live_id = Request()->param('live_id');
        
        $list = Db::name('check_live_log')->where(['live_id' => $live_id])->order('id desc')->paginate();
        
        $this->assign('list', $list);
        $this->assign('title', '音视频监测历史记录');
        
        return $this->fetch();
    }
}
